package com.lnt.spring.conversion;

import com.lnt.spring.bean.User;
import com.lnt.spring.service.UserService;
import com.lnt.spring.SpringTest;
import org.springframework.beans.factory.config.CustomEditorConfigurer;
import org.springframework.context.annotation.Configuration;

import java.beans.PropertyEditor;
import java.util.HashMap;
import java.util.Map;

/**
 * @title : Spring自定义类型转换器
 * @createDate : 2021-11-13 10:45
 * @creater : LuNanTing
 * @className : SpringCustomEditorConfigurer
 */
@Configuration
public class SpringCustomEditorConfigurer {

    /**
     * 可以将jdk自带并且自己已经配置的类型转换纳入到Spring容器中管理
     * @see CustomEditorConfigurer
     * @return
     */
//    @Bean
    public CustomEditorConfigurer customEditorConfigurer(){
        // 声明Spring的类型转换管理
        CustomEditorConfigurer customEditorConfigurer = new CustomEditorConfigurer();

        Map<Class<?> , Class<? extends PropertyEditor>> propertyEditorMap = new HashMap<>();

        // 表示StringToUserPropertyEditor可以将String转换为User.class
        // 在Spring源码中，如果发现当前对象是String，而需要转换的类型是User.class ，就会调用该转换方法
        /**
         * 详见
         * @see SpringTest main()
         * @see UserService user()
         */
        propertyEditorMap.put(User.class, StringToUserPropertyEditor.class);
        customEditorConfigurer.setCustomEditors(propertyEditorMap);
        return customEditorConfigurer;
    }
}
